<template>
	<div class="user">
		<n-form :model="model">
			<n-form-item label="账号">
				<n-input v-model:value="model.username" @keydown.enter.prevent />
			</n-form-item>
			<n-form-item label="密码">
				<n-input v-model:value="model.password" @keydown.enter.prevent />
			</n-form-item>
			<n-form-item label="角色">
				<n-tree-select multiple cascade checkable check-strategy="all" :options="options" :value="model.roles"
                    @update:value="onUpdateValue" />
			</n-form-item>

			<n-space>
				<n-button @click="onAdd">新增</n-button>
				<n-button type="tertiary" @click="onEdit">修改</n-button>
			</n-space>
		</n-form>

		<h4 @click="onLoad">全部</h4>
		<n-space>
			<n-tag closable @close="onDel(i)" v-for="i in list" :key="i._id" @click="onShow(i)">{{ i.username }}</n-tag>
		</n-space>
	</div>
</template>

<script setup lang="ts">
import { computed, onMounted, ref } from "vue";
import { NForm, NInput, NButton, NFormItem, NSpace, NTag, NTreeSelect } from "naive-ui";
import { useUserStore } from "@/stores/user";
import { useRoleStore } from "@/stores/role";
const userStore = useUserStore();
const roleStore = useRoleStore();

onMounted(() => {
	userStore.load();
});

const onAdd = async () => {
	let param = {
		...model.value,
		age: 12
	};
	let res = await userStore.add(param);
	console.log(res);
	userStore.load();
};

const onEdit = async () => {
	let param = {
		...model.value,
		age: 12
	};
	let res = await userStore.update(param);
	console.log(res);
	userStore.load();
};

interface ModelType {
	username: string;
	password: string;
    roles: string[];
	_id: string;
}

const model = ref<ModelType>({
	username: "",
	password: "",
    roles: [],
	_id: ""
});

const list = computed(() => userStore.list);

const options = computed(() => {
    return roleStore.list.map(i => {
        return { key: i._id, label: i.name };
    })
});
const onUpdateValue = (val: any) => {
    model.value.roles = val;
}

const onDel = async (item: any) => {
	console.log(item);
	// list.value = list.value.filter(i => i != item);
	let res = await userStore.remove(item._id);
	console.log(res);
	userStore.load();
};

const onShow = (item: any) => {
	model.value.username = item.username;
	model.value.password = item.password;
	model.value._id = item._id;
    model.value.roles = item.roles || [];
    userStore.getpermissions(item._id);
};

const onLoad = () => {
	userStore.load();
};
</script>
